package com.coffee.admin.service.platform.impl;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.platform.query.PlatformQuery;
import com.coffee.admin.api.platform.rep.PlatformOperateRes;
import com.coffee.admin.api.platform.req.PlatformAccountAddReq;
import com.coffee.admin.api.platform.req.PlatformAccountListReq;
import com.coffee.admin.api.platform.req.PlatformAccountUpdateReq;
import com.coffee.admin.api.platform.result.PlatformResult;
import com.coffee.admin.api.platform.service.PlatformService;
import com.coffee.admin.service.platform.bean.Platform;
import com.coffee.admin.service.platform.dao.PlatformDao;
import com.coffee.admin.service.platform.dao.PlatformRoleRelationDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.DTOUtils;
import com.coffee.core.util.PasswordUtil;
import com.coffee.core.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;


@DubboService(dynamic = true)
public class PlatformServiceImpl implements PlatformService {
    private static final Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
    @Resource
    private PlatformDao platformDao;
    @Resource
    private PlatformRoleRelationDao platformRoleRelationDao;

    @Override
    public Page<PlatformResult> getPager(PlatformQuery param, PagerInfo pr) {
        Page<PlatformResult> pager = new Page<PlatformResult>(pr.getStart(), pr.getPageSize());
        Integer count = platformDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<Platform> list = platformDao.page(param, pr.getStart(), pr.getPageSize());
            pager.setData(DTOUtils.convertList(list, PlatformResult.class));
        }
        return pager;
    }

    @Override
    public Integer count(PlatformQuery param) {
        Integer count = platformDao.count(param);
        return count;
    }

    @Override
    public PlatformResult getDetail(Integer id) {
        Platform item = platformDao.findById(id);
        if (item == null) {
            return null;
        }
        PlatformResult result = new PlatformResult();
        BeanUtilExt.copyProperties(result, item);

        return result;
    }

    @Override
    public List<PlatformResult> getList(PlatformQuery param, PagerInfo pr) {
        List<Platform> list = platformDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, PlatformResult.class);
    }

    @Override
    public List<PlatformResult> getList(PlatformQuery param) {
        List<Platform> list = platformDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, PlatformResult.class);
    }

    @Override
    public List<PlatformResult> getList() {
        PlatformQuery param = new PlatformQuery();
        List<Platform> list = platformDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, PlatformResult.class);
    }


    @Override
    public void delete(Integer id) throws BusinessException {
        Platform platform = this.platformDao.findById(id);
        ValidateBusinessException.assertNonNull(platform, ExceptionEnum.ERROR_1306);
        ValidateBusinessException.assertFalse("Y".equals(platform.getIsAdmin()), ExceptionEnum.ERROR_1307);
        platformDao.deleteById(id);
        //删除账户角色关联表
        logger.info("delete(删除账户角色关联表):operatorId=" + id);
        platformRoleRelationDao.deleteByPlatformId(id);
    }

    @Override
    public void addOrUpdate(PlatformResult result) throws BusinessException {
        Platform item = new Platform();
        BeanUtilExt.copyProperties(item, result);
        if (item.getId() == null) {
            item.setCreateTime(new Date());
            platformDao.insert(item);
        } else {
            Platform tmp = platformDao.findById(item.getId());
            if (tmp == null) {
                throw new BusinessException(ExceptionEnum.ERROR_0002.getCode(), ExceptionEnum.ERROR_0002.getMessage());
            }
            platformDao.updateById(item);
        }
    }

    @Override
    public Map<Integer, PlatformResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, PlatformResult> map = new HashMap<Integer, PlatformResult>();
        List<Platform> list = platformDao.findByIds(StringUtil.setToList(idSet));
        List<PlatformResult> resultList = DTOUtils.convertList(list, PlatformResult.class);
        for (PlatformResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, PlatformResult> getItemMap() {
        Map<Integer, PlatformResult> map = new HashMap<Integer, PlatformResult>();
        PlatformQuery param = new PlatformQuery();
        List<Platform> list = platformDao.page(param, 0, Integer.MAX_VALUE);
        List<PlatformResult> resultList = DTOUtils.convertList(list, PlatformResult.class);
        for (PlatformResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public PlatformResult getPlatformService(PlatformResult result) {
        PlatformResult platformResult = new PlatformResult();
        PlatformQuery param = new PlatformQuery();
        BeanUtilExt.copyProperties(param, result);
        Platform platform = platformDao.findFirst(param);
        if (platform == null)
            return null;
        BeanUtilExt.copyProperties(platformResult, platform);
        return platformResult;
    }

    @Override
    public Page<PlatformOperateRes> findMerchantOperatorListByPage(PlatformAccountListReq params, PagerInfo pagerInfo) throws BusinessException {
        Page<PlatformOperateRes> pageData = new Page<>(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
        PlatformQuery platformQuery = new PlatformQuery();
        BeanUtilExt.copyProperties(platformQuery, params);
        int amount = this.platformDao.count(platformQuery);
        if (amount > 0) {
            List<PlatformOperateRes> platformOperateRes = platformDao.pageByPlatformOperateRes(platformQuery, pagerInfo.getPageIndex(), pagerInfo.getPageSize());
            pageData.setData(platformOperateRes);
        }
        pageData.setAmount(amount);
        return pageData;
    }

    @Override
    public PlatformOperateRes findMerchantOperatorDetail(PlatformAccountListReq params) {
        PlatformQuery platformQuery = new PlatformQuery();
        BeanUtilExt.copyProperties(platformQuery, params);
        PlatformOperateRes merchantOperatorDetail = platformDao.findMerchantOperatorDetail(platformQuery);
        return merchantOperatorDetail;
    }

    @Override
    public void insertPlatformOperate(PlatformAccountAddReq params) throws BusinessException {
        logger.info("insertPlatformOperate", params);
        ValidateBusinessException.assertStringNotBlank(params.getName(), ExceptionEnum.ERROR_1301);
        ValidateBusinessException.assertStringNotBlank(params.getMobile(), ExceptionEnum.ERROR_1302);
        List<Integer> roleIdList = params.getRoleIdList();
        ValidateBusinessException.assertCollectionNotEmpty(roleIdList, ExceptionEnum.ERROR_1303);
        ValidateBusinessException.assertStringNotBlank(params.getPassword(), ExceptionEnum.ERROR_1304);

        PlatformQuery query = new PlatformQuery();
        query.setMobile(params.getMobile());
        Platform platform = platformDao.findFirst(query);
        Integer operatorId = null;
        if (platform != null) {
            throw new BusinessException(ExceptionEnum.ERROR_1305.getCode(), ExceptionEnum.ERROR_1305.getMessage());
        }
        platform = new Platform();
        BeanUtilExt.copyProperties(platform, params);
        platform.setCreateTime(new Date());
        platform.setPassword(PasswordUtil.getPass(params.getPassword()));
        // 添加后默认为可用
        platform.setIsEnable("Y");
        platform.setIsAdmin("N");
        platform.setPid(params.getPlatformId());
        logger.info("insertPlatformOperate(添加账户)", platform);
        this.platformDao.insert(platform);
        operatorId = platform.getId();
        logger.info("insertEpMerchantOperator(添加账户角色关联表):", "operatorId=" + operatorId + ",roleIdList=" + JSONObject.toJSONString(roleIdList));
        platformRoleRelationDao.insertBatch(operatorId, roleIdList);
    }

    @Override
    public void updatePlatformOperate(PlatformAccountUpdateReq params) throws BusinessException {
        logger.info("updatePlatformOperate", params);
        ValidateBusinessException.assertStringNotBlank(params.getName(), ExceptionEnum.ERROR_1301);
        ValidateBusinessException.assertStringNotBlank(params.getMobile(), ExceptionEnum.ERROR_1302);
        List<Integer> roleIdList = params.getRoleIdList();
        ValidateBusinessException.assertCollectionNotEmpty(roleIdList, ExceptionEnum.ERROR_1303);

        Platform platform = this.platformDao.findById(params.getId());
        ValidateBusinessException.assertNonNull(platform, ExceptionEnum.ERROR_1306);
        Integer operatorId = platform.getId();
        ValidateBusinessException.assertFalse("Y".equals(platform.getIsAdmin()), ExceptionEnum.ERROR_1307);
        Platform updatePlatform = new Platform();
        BeanUtilExt.copyProperties(updatePlatform, params);
        logger.info("updatePlatformOperate(修改账户信息):" + JSONObject.toJSONString(updatePlatform));
        platformDao.updateById(updatePlatform);

        //删除账户角色关联表
        logger.info("updatePlatformOperate(删除账户角色关联表):operatorId=" + operatorId);
        platformRoleRelationDao.deleteByPlatformId(operatorId);

        logger.info("updatePlatformOperate(添加账户角色关联表):", "operatorId=" + operatorId + ",roleIdList=" + JSONObject.toJSONString(roleIdList));
        platformRoleRelationDao.insertBatch(operatorId, roleIdList);
    }

    @Override
    public void updateIsEnable(Integer platformId, String isEnable) throws BusinessException {
        logger.info(new StringBuilder("updateIsEnable:operateId=").append(platformId).append(",isEnable=").append(isEnable).toString());
        ValidateBusinessException.assertNonNull(platformId, ExceptionEnum.ERROR_1303);
        ValidateBusinessException.assertStringNotBlank(isEnable, ExceptionEnum.ERROR_1308);
        Platform platform = this.platformDao.findById(platformId);
        ValidateBusinessException.assertNonNull(platform, ExceptionEnum.ERROR_1306);
        ValidateBusinessException.assertFalse("Y".equals(platform.getIsAdmin()), ExceptionEnum.ERROR_1307);

        Platform param = new Platform();
        param.setId(platformId);
        param.setIsEnable(isEnable);
        logger.info("updateIsEnable(启用禁用登录操作员):" + JSONObject.toJSONString(param));
        platformDao.updateById(param);
    }


}
